import threading
import requests
import time
from queue import Queue

number = 128
headers = {
    "Authority":"qlong.p5w.net",
    "Method":"GET",
    "Scheme":"https",
    "Accept":"*/*",
    "Accept-Encoding":"gzip, deflate, br",
    "Accept-Language":"zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
    "Origin":"https://rs.p5w.net",
    "Referer":"https://rs.p5w.net/",
    "Sec-Ch-Ua":"\"Not.A/Brand\";v=\"8\", \"Chromium\";v=\"114\", \"Google Chrome\";v=\"114\"",
    "Sec-Ch-Ua-Mobile":  "?0",
    "Sec-Ch-Ua-Platform": "macOS",
    "Sec-Fetch-Dest":"empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-site",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}


class Producer(threading.Thread):

    def __init__(self, url_queue, data_queue, *args, **kwargs):
        super(Producer, self).__init__(*args, **kwargs)
        self.url_queue = url_queue
        self.data_queue = data_queue

    def run(self) -> None:
        # 从url_page中拿url
        while True:
            if self.url_queue.empty():
                print("~~~~~~ 读取完成 ~~~~~~")
                break
            url = self.url_queue.get()
            print("~~~~~~ 读:" + url)
            self.get_data(url)

    def get_data(self, url):
        res = requests.get(url, headers=headers)
        data = res.content

        if res.status_code != 200:
            print("status:" + str(res.status_code))
            print(res.content)

        self.data_queue.put(data)


class Consumer(threading.Thread):

    def __init__(self, url_queue, data_queue, *args, **kwargs):
        super(Consumer, self).__init__(*args, **kwargs)
        self.url_queue = url_queue
        self.data_queue = data_queue

    def run(self) -> None:
        while True:
            if self.data_queue.empty():
                if self.url_queue.empty():
                    print("~~~~~~ 写入完成~~~~~~")
                    return
            data = self.data_queue.get()
            with open("{}.ts".format(number + 1), 'ab+') as f:
                f.write(data)
                f.flush()


def main():
    url_queue = Queue()
    data_queue = Queue()
    # https://qlong.p5w.net/u/21859/m3u8/1920x1080/1080-b4fcc8324a090ab9d64378fb90c88924/00000.ts
    # 准备url
    for x in range(number + 1):
        # https://qlong.p5w.net/u/21859/m3u8/0x0/0-b4fcc8324a090ab9d64378fb90c88924/00127.ts
        url = 'https://qlong.p5w.net/u/21859/m3u8/1920x1080/1080-b4fcc8324a090ab9d64378fb90c88924/{:05d}.ts'.format(x)
        url_queue.put(url)

    # 创建生产者、消费者进程
    Producer(url_queue, data_queue).start()
    Consumer(url_queue, data_queue).start()


if __name__ == '__main__':
    main()